package com.itzyf.pokemondata.activity

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.itzyf.pokemondata.R
import com.itzyf.pokemondata.bean.DbDrillDo
import com.itzyf.pokemondata.utils.OnRefreshListener
import com.itzyf.pokemondata.utils.setOnRefreshListener
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.tydic.baselibrary.activity.BaseActivity
import kotlinx.android.synthetic.main.activity_drill_record.*
import org.litepal.LitePal
import org.litepal.extension.deleteAll
import java.text.SimpleDateFormat
import java.util.*

/**
 * @author 依风听雨
 * @version 创建时间：2019/02/06 19:57
 */
class DrillRecordActivity : BaseActivity() {
    var mDatas: MutableList<DbDrillDo?> = ArrayList()
    var index = 0
    private lateinit var mAdapter: QuickAdapter

    override fun handlerActivity() {
        mAdapter = QuickAdapter(R.layout.item_drill, mDatas)
        rv_list.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
        rv_list.adapter = mAdapter

        mAdapter.setOnLoadMoreListener({ queryDatas(index++) }, rv_list)

        pull_to_refresh.setOnRefreshListener(object : OnRefreshListener {
            override fun onRefresh() {
                index = 0
                queryDatas(index)
            }
        })
        queryDatas(0)

        mAdapter.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(this, EditDrillActivity::class.java)
            intent.putExtra("drillId", mDatas[position]?.id)
            startActivityForResult(intent, 2)
        }


        if (sp.getBoolean("showDrillTips", true)) {
            showTipMessage()
            sp.edit().putBoolean("showDrillTips", false).apply()
        }
    }

    private fun queryDatas(index: Int = 0, pageSize: Int = 20) {
        val dataList =
            LitePal
                .limit(pageSize)
                .offset(index * pageSize)
                .order("date desc")
                .find(DbDrillDo::class.java)
        if (index == 0) {
            mDatas.clear()
            pull_to_refresh.finishRefresh()
        }

        mDatas.addAll(dataList)
        if (dataList.size < pageSize) {
            mAdapter.loadMoreEnd()
        } else {
            mAdapter.loadMoreComplete()
        }
        mAdapter.notifyDataSetChanged()

    }

    override fun getContentViewId() = R.layout.activity_drill_record

    override fun getToolbarTitle() = "存钻记录"

    internal inner class QuickAdapter(layoutResId: Int, data: List<DbDrillDo?>) :
        BaseQuickAdapter<DbDrillDo, BaseViewHolder>(layoutResId, data) {
        private val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE)
        override fun convert(helper: BaseViewHolder, item: DbDrillDo?) {
            item?.let {
                helper.setText(R.id.text, sdf.format(it.date))
                helper.setText(R.id.tvRecord, "${it.record}钻")
                if (helper.layoutPosition + 1 < mDatas.size) {
                    val increase = it.record - mDatas[helper.layoutPosition + 1]!!.record
                    if (increase >= 0) {
                        helper.setTextColor(R.id.tvIncrease, Color.RED)
                        helper.setText(R.id.tvIncrease, "+${increase}钻")
                    } else {
                        helper.setTextColor(R.id.tvIncrease, Color.GREEN)
                        helper.setText(R.id.tvIncrease, "${increase}钻")
                    }
                } else {
                    helper.setText(R.id.tvIncrease, "")
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            index = 0
            queryDatas(index)
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.add, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        if (item?.itemId == R.id.action_add) {
            val intent = Intent(this, EditDrillActivity::class.java)
            startActivityForResult(intent, 1)
            return true
        } else if (item?.itemId == R.id.action_clear) {
            QMUIDialog.MessageDialogBuilder(this)
                .setTitle("提示")
                .setMessage("将要清空所有的存钻记录，是否确定？")
                .addAction("取消") { dialog, _ ->
                    dialog.dismiss()
                }
                .addAction("确定") { dialog, _ ->
                    LitePal.deleteAll(DbDrillDo::class.java)
                    mDatas.clear()
                    mAdapter.notifyDataSetChanged()
                    dialog.dismiss()
                }
                .show()
        }
        return super.onOptionsItemSelected(item)
    }

    private fun showTipMessage() {
        QMUIDialog.MessageDialogBuilder(this)
            .setTitle("请注意")
            .setMessage("数据保存在本地，如卸载重装或者清除数据会导致数据丢失，关于APP中清除缓存及版本更新不影响")
            .addAction("关闭") { dialog, _ ->
                dialog.dismiss()
            }
            .show()

    }
}